<?php
/***
 * 赠品Service
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */

namespace App\Services\GiftService;


use App\Services\ImgServices\ImgTool;
use App\Services\ProductsService\ProductTool;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\Tool\DataBase\SQL;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GiftApiService
{
    private $productTool;
    /**
     * GiftApiService constructor.
     */
    public function __construct(ProductTool $productTool)
    {
        $this->productTool=$productTool;
    }

    /**
    获取产品赠品
     */
    static function getProductGift($input){
        //判断产品是否有赠品
        $gifts	= array();
        $time	= time();
        $product_id=$input['product_id'];
        $gift_c	= self::GiftIdGet(array('table'=>'favorable_gifts',
            'where'=>array('type'=>2,
                'reg_id'=>$input['product_id'],
                'state'=>1),
            'time'=>$time));
        $product_temp_id=GiftTool::getProductTempIdByProductId($product_id);
        $brand_id='';
        if(!empty($product_id)){
            $brand_id=ProductTempTool::getBrandIdByProdTempId($product_id);
        }
        //产品id  产品模板id 品牌 订单额度

        foreach($gift_c as $gi){
            //暂时只做，当赠品捆绑到某一产品的情况
            $gift	= self::getGiftInfo(array('id'=>$gi->gift_id));
            $gift_num=0;//
            if(empty($gift)||($gift->num<1)) {
                continue;
            }else{
                $gift_num=$gift->num;
            }
            $gift->num=1;
            $gift->fg_id = $gi->id;
            $gift->gift_type = 'product';
            if(!isset($input['total_fee'])||(isset($input['total_fee'])&&($gi->quota==0))){
                $gifts[] = $gift;
            }elseif((isset($input['total_fee'])&&$input['total_fee']>=$gi->quota)){
                $gift->num	= empty(floatval($gi->quota))?1:floor($input['total_fee']/$gi->quota);
                $gift->num=intval($gift->num);
                //$gift_num 赠品总剩余数，$gift->num 需要赠送数量
                $gift->num  = $gift->num > $gift_num?$gift_num:$gift->num;
                if($gift->num>0)
                    $gifts[] = $gift;
            }
        }
        /*
        $product_id	= SQL::pluck(array('table'=>'products',
                                       'where'=>array('product_id'=>$input['product_id']),
                                       'pluck'=>'product_id'));
        if(isset($product_id)){
            $gift_p	= self::GiftIdGet(array('table'=>'favorable_gifts',
                                            'where'=>array('type'=>1,
                                                           'reg_id'=>$product_id,
                                                           'state'=>1),
                                            'time'=>$time));
            //dd($gift_p);
            foreach($gift_p as $gi){
                if($gi->quota==0||(isset($input['total_fee'])&&$input['total_fee']>=$gi->quota)){
                    $gift	= self::getGiftInfo(array('id'=>$gi->gift_id));
                    if(isset($gift)){
                        $gift->fg_id = $gi->id;
                        $gift->gift_type = 'product';
                        $gift->num	= empty(floatval($gi->quota))?1:floor($input['total_fee']/$gi->quota);
                        $gift->num  = $gift->num > $gi->num?$gi->num:$gift->num;
                        if($gift->num>0)
                            $gifts[] = $gift;
                    }
                }
            }
        }



        $product	= SQL::first(array('table'=>'products',
                                       'where'=>array('product_id'=>$product_id)));

        if(isset($product)){
            $gift_b	= self::GiftIdGet(array('table'=>'favorable_gifts',
                                        'where'=>array('type'=>3,
                                                       'reg_id'=>$product->brand_id,
                                                       'state'=>1),
                                        'time'=>$time));

            foreach($gift_b as $gi){
                if($gi->quota==0||(isset($input['total_fee'])&&$input['total_fee']>=$gi->quota)){
                    $gift	= self::getGiftInfo(array('id'=>$gi->gift_id,'activity_id'=>$gi->activity_id));
                    if(isset($gift)){
                        $gift->fg_id = $gi->id;
                        $gift->gift_type = 'brand';

                        $gift->num	= empty(floatval($gi->quota))?1:floor($input['total_fee']/$gi->quota);
                        $gift->num  = $gift->num > $gi->num?$gi->num:$gift->num;
                        if($gift->num>0)
                            $gifts[] = $gift;
                    }
                }
            }
        }


        $gift_q	= self::GiftIdGet(array('table'=>'favorable_gifts',
                                        'where'=>array('type'=>0,
                                                       'state'=>1),
                                        'time'=>$time));
        foreach($gift_q as $gi){
            if($gi->quota==0||(isset($input['total_fee'])&&$input['total_fee']>=$gi->quota)){
                $gift	= self::getGiftInfo(array('id'=>$gi->gift_id,'activity_id'=>$gi->activity_id));
                if(isset($gift)){
                    $gift->fg_id = $gi->id;
                    $gift->gift_type = 'quota';
                    $gift->num	= empty(floatval($gi->quota))?1:floor($input['total_fee']/$gi->quota);
                    $gift->num  = $gift->num > $gi->num?$gi->num:$gift->num;
                    if($gift->num>0)
                        $gifts[] = $gift;
                }
            }
        }
*/
        return $gifts;
    }
    /**
    获取赠品详情
     */
    static function getGiftInfo($input){
        $gift	= SQL::first(array('table'=>'gifts',
            'where'=>array('id'=>$input['id'],
                'state'=>1)));
        if($gift!==null){
            $gift->thumbnail = ImgTool::getImgUrlByImgPath($gift->thumbnail);
            $gift->original_image = ImgTool::getImgUrlByImgPath($gift->original_image);
            return $gift;
        }
        return '';
    }

    /***
     * 获取对应资源绑定的赠品
     * @param $input
     * @return mixed
     */
    static function GiftIdGet($input){
        $lists	= DB::table('favorable_gifts')
            ->where($input['where'])
            ->where('begin_time','<=',$input['time'])
            ->where('end_time','>',$input['time'])
            ->orderBy('created_at','desc')
            ->get()
            ->toArray();
        return $lists;
    }

    /***
     * 查看资源在当前有限时间内是否有绑定赠品
     * @param $reg_id 资源id
     * @param $type   绑定类型 0满额度 1产品模板 2产品 3品牌
     * @param $time   时间戳 一般是当前时间戳
     * @return array
     */
    static function getGiftIdsByRegIdAndType($reg_id,$type,$time){
        $lists	= DB::table('favorable_gifts')
            ->where(array('state'=>1,'type'=>$type,'reg_id'=>$reg_id,))
            ->where('num','>',0)
            ->where('begin_time','<=',$time)
            ->where('end_time','>',$time)
            ->orderBy('updated_at','desc')
            ->pluck('gift_id')
            ->distinct()
            ->toArray();
        return empty($lists)?array():$lists;
    }
    /***
     * 增加库存
     * @param $gift_id
     * @param int $num
     * @return int
     */
    public static function incrementStock($gift_id,$num=1){
        if(!is_int($gift_id)||(!is_int($num)||($num<0))){
            return 0;
        }
        $time_str=date("Y-m-d H:i:s", time());
        Log::info( $time_str.',begin 增加库存  **************************');
        Log::info(array('gift_id'=>$gift_id,'num'=>$num));
        Log::info( $time_str.',end 增加库存  **************************');
        $stock=self::getGiftStock($gift_id);
        if(empty($stock)||($stock<$num)||!is_int($stock)){
            return 0;
        }
        $stock+=$num;
        $res=self::updateGiftStockInDB($gift_id,$stock);
        return $res;
    }

    /***
     * 减少库存
     * @param $gift_id
     * @param int $num
     * @return int
     */
    public static function decrementStock($gift_id,$num=1){
        $time_str=date("Y-m-d H:i:s", time());
        Log::info( $time_str.',begin 减少库存  **************************');
        Log::info(array('gift_id'=>$gift_id,'num'=>$num));
        Log::info( $time_str.',end 减少库存  **************************');
        if(!is_int($gift_id)||(!is_int($num)||($num<0))){
            return 0;
        }
        $stock=self::getGiftStock($gift_id);
        if(empty($stock)||($stock<$num)||!is_int($stock)||($stock<$num)){
            return 0;
        }
        $stock-=$num;
        $res=self::updateGiftStockInDB($gift_id,$stock);
        return $res;
    }
    /***
     * 获取赠品库存
     * @param $gift_id
     * @return null
     */
    public static function getGiftStock($gift_id){
        if(!is_int($gift_id)){
            return 0;
        }
        $time=time();
        $num= DB::table('gifts')->where(array('state'=>1,'id'=>$gift_id))
            ->where('begin_time','<=',$time)
            ->where('end_time','>',$time)
            ->value('num');
        return empty($num)?0:$num;
    }

    /***
     * 更新库存
     * @param $gift_id
     * @param $num
     * @return int
     */
    private static function updateGiftStockInDB($gift_id,$num){
        if(!is_int($gift_id)){
            return 0;
        }
        $num= DB::table('gifts')->where(array('state'=>1,'id'=>$gift_id))
            ->update(array(
                'updated_at'=>time(),
                'num'=>$num
            ));
        return $num;
    }
}
